package com.atguigu.product.service.impl;

import com.atguigu.product.entity.AttrEntity;
import com.atguigu.product.service.AttrService;
import com.atguigu.product.vo.AttrGroupWithAttrVo;
import com.atguigu.product.vo.SpuItemAttrGroupVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.product.dao.AttrGroupDao;
import com.atguigu.product.entity.AttrGroupEntity;
import com.atguigu.product.service.AttrGroupService;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {
  @Resource
  private AttrService attrService;


  @Override
  public PageUtils queryPage(Map<String, Object> params) {
    IPage<AttrGroupEntity> page = this.page(
      new Query<AttrGroupEntity>().getPage(params),
      new QueryWrapper<>()
    );

    return new PageUtils(page);
  }

  @Override
  public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
    String key = (String) params.get("key");
    QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<AttrGroupEntity>();
    if (catelogId != 0) {
      wrapper.eq("catelog_id", catelogId);
      if (!StringUtils.isEmpty(key)) {
        wrapper.and(obj -> obj.eq("attr_group_id", key).or().like("attr_group_name", key));
      }
    }
    IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params), wrapper);
    return new PageUtils(page);
  }

  @Override
  public List<AttrGroupWithAttrVo> getAttrGroupWithAttrByCatelogId(Long catId) {
    List<AttrGroupEntity> attrGroupEntities = baseMapper.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catId));
    List<AttrGroupWithAttrVo> collect = attrGroupEntities.stream().map(group -> {
        AttrGroupWithAttrVo vo = new AttrGroupWithAttrVo();
        BeanUtils.copyProperties(group, vo);
        List<AttrEntity> relationAttr = attrService.getRelationAttr(group.getAttrGroupId());
        vo.setAttrs(relationAttr);
        return vo;
      }
    ).collect(Collectors.toList());
    return collect;
  }

  @Override
  public List<SpuItemAttrGroupVo> getAttrGroupWithAttrsBySpuId(Long spuId, Long catalonId) {

    List<SpuItemAttrGroupVo> vos = baseMapper.getAttrGroupWithAttrsBySpuId(spuId, catalonId);

    return vos;
  }

}
